﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Lucene.Net;
using Lucene.Net.Analysis;
using Lucene.China;
using System.IO;
using System.Data;
using System.Collections;
using BLL.IntelligenceSearch;

using System.Text.RegularExpressions;
using Maticsoft.DBUtility;

namespace BLL
{
    public class SearchBLL
    {

        public static int AddGuessWord(string guessWord)
        {
            string sql = "insert into search_guessword (guessword) values ('" + guessWord + "')";
            return DbHelperOra.ExecuteSql(sql);
        }

        public static int DeleteGuessWordByWord(string word)
        {
            string sql = "delete from search_guessword where guessword = '" + word.Trim() + "'";
            return DbHelperOra.ExecuteSql(sql);
        }

        public static DataSet GetGuessWordFromDB(string input)
        {
            string sql = "select * from search_guessword where guessword like '%" + input.Trim() + "%'";
            return DbHelperOra.Query(sql);
        }

        public static DataSet GetGuessWordFromCache(string input)
        {
            GuessWordCache guessCache = GuessWordCache.GetInstance();

            if ((DateTime.Now - guessCache.RefreshTime).TotalMilliseconds > 1000000 * 60)//超过1000分钟
            {
                guessCache.RefreshDB();
            }

            DataRow [] drs = guessCache.GuessWordDataSet.Tables[0].Select("guessword like '" + input + "%'");
            DataSet ds = new DataSet();
            ds = guessCache.GuessWordDataSet.Clone();
            foreach (DataRow dr in drs)
            {
                ds.Tables[0].ImportRow(dr);
            }
            
            
            return ds;

        }

        public static List<String> SplitWord(string s)
        {
            
            //StringBuilder sb = new StringBuilder();
            //sb.Remove(0, sb.Length);
            string t1 = "";
            List<String> wordList = new List<String>();
            Analyzer analyzer = new Lucene.China.ChineseAnalyzer();
            StringReader sr = new StringReader(s);
            TokenStream stream = analyzer.TokenStream(null, sr);

            //long begin = System.DateTime.Now.Ticks;
            Token t = stream.Next();
            while (t != null)
            {
                t1 = t.ToString();   //显示格式： (关键词,0,2) ，需要处理
                t1 = t1.Replace("(", "");
                char[] separator = { ',' };
                t1 = t1.Split(separator)[0];

                //sb.Append( + t1 + "\r\n");
                wordList.Add(t1);
                t = stream.Next();
                
            }
            //s2 = sb.ToString();
            //long end = System.DateTime.Now.Ticks; //100毫微秒
            //int time = (int)((end - begin) / 10000); //ms

            //s2 += "耗时" + (time) + "ms \r\n=================================\r\n";
            return wordList;
        }

        public static ArrayList DoSearch(String searchWord,String searchWhere,int maxReturnCount)
        {
            //新增或者更新搜索热门词
            HotWordIncrease(searchWord);

            ASearch aSearch;
            string[] searchWords = PrepareWordSplitBySpace(searchWord);
            List<String> searchWordList = new List<string>();
            foreach(String s in searchWords)
            {
                List<string> list = SplitWord(searchWord);
                searchWordList.AddRange(list);
            }

            
            if (searchWhere.Equals("C"))
            {
                aSearch = new SearchCompany(searchWordList, maxReturnCount);
                return aSearch.DoSearch();
            }
            else if(searchWhere.Equals("P"))
            {
                aSearch = new SearchPerson(searchWordList, maxReturnCount);
                return aSearch.DoSearch();
            }
            else if (searchWhere.Equals("S"))
            {
                aSearch = new SearchShop(searchWordList, maxReturnCount);
                return aSearch.DoSearch();
            }
            else if (searchWhere.Equals("O"))
            {
                aSearch = new SearchOrganization(searchWordList, maxReturnCount);
                return aSearch.DoSearch();
            }
            else
            {
                throw new ApplicationException("输入的搜索类型未知，输入的类型为" + searchWhere);
            }
        }

        public static ArrayList DoSearchAll(String searchWord, String searchWhere, int maxReturnCount)
        {
            ASearch aSearch;
            string[] searchWords = PrepareWordSplitBySpace(searchWord);
            List<String> searchWordList = new List<string>();
            foreach (String s in searchWords)
            {
                List<string> list = SplitWord(searchWord);
                searchWordList.AddRange(list);
            }


            if (searchWhere.Equals("C"))
            {
                aSearch = new SearchCompany(searchWordList, maxReturnCount);
                return aSearch.DoSearchAll();
            }
            else if (searchWhere.Equals("P"))
            {
                aSearch = new SearchPerson(searchWordList, maxReturnCount);
                return aSearch.DoSearchAll();
            }
            else if (searchWhere.Equals("S"))
            {
                aSearch = new SearchShop(searchWordList, maxReturnCount);
                return aSearch.DoSearchAll();
            }
            else if (searchWhere.Equals("O"))
            {
                aSearch = new SearchOrganization(searchWordList, maxReturnCount);
                return aSearch.DoSearchAll();
            }
            else
            {
                throw new ApplicationException("输入的搜索类型未知，输入的类型为" + searchWhere);
            }
        }
        
        /// <summary>
        /// 以空格分隔搜索词，做预分词
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static string [] PrepareWordSplitBySpace(string s)
        {
           return s.Split(" ".ToCharArray());
        }
        

        //public static string [] GetGuessWord(string substring)
        //{
        //    List<string> items = new List<string>();
        //    SEARCH_GUESSWORD_DAL dal = new SEARCH_GUESSWORD_DAL();
        //    DataSet ds = dal.GetGuessWordBySearch(substring);
        //    if (ds.Tables[0].Rows.Count == 0)
        //    {
        //        return null;
        //    }
        //    else
        //    {
        //        foreach (DataRow dr in ds.Tables[0].Rows)
        //        {
        //            items.Add(dr["guessword"].ToString());
        //        }
        //        return items.ToArray();
        //    }
            
            
        //}
        /// <summary>
        /// 用户输入的搜索词自增1
        /// 如果用户输入的搜索词没有再hotword中出现，那么新增这个搜索词，搜索次数设为1
        /// 如果用户输入搜索词在hotword里面出现过，那么这个词的搜索次数+1
        /// </summary>
        /// <param name="hotWord">用户搜索词</param>
        /// <returns>1表示新增或者更新1行，0表示新增或者更新0行</returns>
        private static int HotWordIncrease(string hotWord)
        {
            string prepareHotWord = hotWord.Trim();//去掉两边空格
            
            //把里面包含多个空格的字符串变成一个空格，
            //这样可以减少相同文字，但是不同空格造成的冗余
            string s = Regex.Replace(prepareHotWord,"\\s"," ");

            string sqlselect = "select id,hotword,count from search_hotword where hotword = '"+s+"'";
            DataSet ds = DbHelperOra.Query(sqlselect);
            int i = 0;
            if (ds.Tables[0].Rows.Count == 0)
            {
                //没有找到这个搜索词
                //add
                string sqlinsert = "insert into search_hotword (hotword,count) values('"+s+"',"+1+")";
                i= DbHelperOra.ExecuteSql(sqlinsert);
            }
            else
            {
                //找到这个搜索词
                //update
                
                int id = Convert.ToInt32(ds.Tables[0].Rows[0]["id"]);
                
                string sqlupdate = "update search_hotword set count = count+1 where id = " + id;
                i= DbHelperOra.ExecuteSql(sqlupdate);
            }

            return i;

        }

        public static DataSet GetHotWord(string searchWord)
        {
            string sql = "select hotword,count from search_hotword ";
            if (!string.IsNullOrEmpty(searchWord))
            {
                sql = sql + "where hotword like '%" + searchWord + "%'";
            }
            return DbHelperOra.Query(sql);
        }
        
        //联系方式搜索
        #region 
        /// <summary>
        /// 在user_company user_person user_shop里面搜索qq号
        /// </summary>
        /// <param name="qq"></param>
        /// <returns></returns>
        public static DataSet SearchQQ(string qq)
        {
            string sqlstr = "select * from v_usercontactbrief where qq like '%" + qq + "%'";
            return DbHelperOra.Query(sqlstr);
        }
        /// <summary>
        /// 在user_company user_person user_shop里面搜索weibo网址
        /// </summary>
        /// <param name="qq"></param>
        /// <returns></returns>
        public static DataSet SearchWeibo(string weibo)
        {
            string sqlstr = "select * from v_usercontactbrief where weibo like '%" + weibo + "%'";
            return DbHelperOra.Query(sqlstr);
        }
        /// <summary>
        /// 在user_company user_person user_shop里面搜索email
        /// </summary>
        /// <param name="qq"></param>
        /// <returns></returns>
        public static DataSet SearchEmail(string email)
        {
            string sqlstr = "select * from v_usercontactbrief where email like '%" + email + "%'";
            return DbHelperOra.Query(sqlstr);
        }
        /// <summary>
        /// 搜索（淘宝）网店功能
        /// 在user_company user_person user_shop里面搜索website
        /// </summary>
        /// <param name="website"></param>
        /// <returns></returns>
        public static DataSet SearchWebSite(string website)
        {
            string sqlstr = "select * from v_usercontactbrief where website like '%" + website + "%'";
            return DbHelperOra.Query(sqlstr);
        }
        #endregion 
    }
}
